/**
 * <p>Copyright: Copyright (c) 2012</p>
 * <p>Company: �������ƿƼ����޹�˾</p>
 * <p>Aug 8, 2012 2:34:46 PM</p>
 * @author wangyunpeng
 * @version 1.0
 */
package com.ce.study.socketpool;

import java.util.Map;

import org.apache.log4j.Logger;

import com.ce.utils.TransformUtil;


/** 
 * desc:
 * <p>�����ˣ�wangyunpeng �������ڣ�Aug 8, 2012 </p>
 * @version V1.0  
 */
public abstract class CM20MessageBase{
	public static Logger log = Logger.getLogger(CM20MessageBase.class);
	protected static String VER_4 = "CM20";
	protected String FMT_4 = "JAVA";
	protected static String EC_2 = "00";
	protected static String CS_2 = "GB";
	protected String LEN_8 = "";
	
	protected static int fixLen = 20;
	
	protected int bodyLen = -1;
	protected Map<String, String> mbody = null;
	protected byte[] bbody = null;
	protected Class<?> cls;
	
	private CM20MessageBase() {
	}
	public CM20MessageBase(Class<?> cls) {
		this();
		this.cls = cls;
	}
	public CM20MessageBase(String fmt_4, Map<String, String> mbody) {
		this.FMT_4 = fmt_4;
		this.mbody = mbody;
	}
	
	public abstract Object getBodyObject() throws Exception;
	public abstract void encode() throws Exception;
	
	public void decode(byte[] msg) throws Exception {
		if(msg == null || msg.length == 0) {
			log.debug("message is null or empty!");
			throw new Exception("message is null or empty!");
		}
		parseHead(msg);
		parseBody(msg);
	}
	
	public int getBodySize() {
		return bodyLen;
	}
	
	public byte[] getBody() {
		return bbody;
	}
	
	public byte[] getMessage() throws Exception {
		String head = getStringHead();
		//������ͷ�ͱ�����ϲ���ɱ���
		return TransformUtil.mergeByteArray(head.getBytes(), this.bbody);
	}
	protected String getStringHead() throws Exception {
		return VER_4+this.FMT_4+EC_2+CS_2+this.LEN_8;
	}
	protected void parseHead(byte[] msg) {
		byte[] head = new byte[fixLen];
		System.arraycopy(msg, 0, head, 0, fixLen);
		String sh = new String(head);
		this.FMT_4 = sh.substring(4, 8);
		this.LEN_8 = sh.substring(12, 20);
		this.bodyLen = Integer.valueOf(this.LEN_8) - fixLen;
	}
	protected void parseBody(byte[] msg) throws Exception {
		this.bbody = new byte[bodyLen];
		System.arraycopy(msg, fixLen, this.bbody, 0, bodyLen);
	}
	
	public void printMessage() throws Exception {
		log.debug("head:"+getStringHead());
		log.debug("body length:"+this.bodyLen);
		log.debug("body content:"+TransformUtil.bytesToHexString(this.bbody));
	}
}
